#include <gtk/gtk.h>
#include <webkit/webkit.h>
#include <fstream>
#include <sstream>
#include <string>
#include <unistd.h>
#include "SimpleLogging.h"

static void destroyWindowCb(GtkWidget* widget, GtkWidget* window);
static gboolean closeWebViewCb(WebKitWebView* webView, GtkWidget* window);
static void loadStatusCb(WebKitWebView *web_view, GParamSpec *pspec, void* context);
static void handleLoadFinished(WebKitWebView *web_view, void* context);
static void lbh_resource_request_starting_cb(WebKitWebView *web_view, WebKitWebFrame *frame, WebKitWebResource *resource, WebKitNetworkRequest *request, WebKitNetworkResponse *response,gpointer data);
static void headerForeachFunc(const char *name, const char *value, gpointer data);
static std::string scriptStr;
static bool finished;

int main(int argc, char* argv[])
{
	SLOG::SetInfoLevel();
	
	std::ifstream file("data/ameblo_tpl.js" );
	std::stringstream buffer;
	buffer << file.rdbuf();
	scriptStr = buffer.str();

	// yolongyi
	g_thread_init(NULL);
	gtk_init(&argc, &argv);
	SLOG(DEBUG) << "gtk_init";

	WebKitWebView *webView = WEBKIT_WEB_VIEW(webkit_web_view_new());
	
	WebKitWebSettings *settings = webkit_web_view_get_settings(webView);
	g_object_set(G_OBJECT(settings), "auto-load-images", FALSE, NULL);
	g_object_set(G_OBJECT(settings), "enable-scripts", FALSE, NULL);
	g_object_set(G_OBJECT(settings), "enable-spell-checking", FALSE, NULL);
	g_object_set(G_OBJECT(settings), "auto-resize-window", FALSE, NULL);
	g_object_set(G_OBJECT(settings), "enable-offline-web-application-cache", FALSE, NULL);
	g_object_set(G_OBJECT(settings), "enable-plugins", FALSE, NULL);
	g_object_set(G_OBJECT(settings), "print-backgrounds", FALSE, NULL);
	g_object_set(G_OBJECT(settings), "enable-java-applet", FALSE, NULL);
	g_object_set(G_OBJECT(settings), "enable-dns-prefetching", FALSE, NULL);
	g_object_set(G_OBJECT(settings), "enable-default-context-menu", FALSE, NULL);
	
	bool allow_load = false;
	g_signal_connect(webView, "notify::load-status", G_CALLBACK(loadStatusCb), NULL);
	g_signal_connect(webView, "resource-request-starting", G_CALLBACK(lbh_resource_request_starting_cb), &allow_load);
		
	while(true) {
		//usleep(1 * 1000 * 1000);
		finished = false;
		allow_load = true;
		
		/*
		std::ifstream file("data/ameblo.html" );
		std::stringstream htmlBuffer;
		htmlBuffer << file.rdbuf();
		string html = htmlBuffer.str();
		*/
		
		WebKitWebFrame *frame = webkit_web_view_get_main_frame(webView);
		webkit_web_frame_load_uri(frame, "file:///home/yolongyi/shukelton-desk/TestWebKitGtk/data/ameblo.html");
		//webkit_web_frame_load_string(frame, html.c_str(), NULL, NULL, "http://ameblo.jp/kinako0309/entry-10035224746.html");

		while(!finished) {
			while(!finished && gtk_events_pending ()){
				gtk_main_iteration();
			}
			//usleep(10 * 1000);
		}
	}

	return 0;
}

static void destroyWindowCb(GtkWidget* widget, GtkWidget* window)
{
	gtk_main_quit();

}

static gboolean closeWebViewCb(WebKitWebView* webView, GtkWidget* window)
{
	gtk_widget_destroy(window);

	return TRUE;
}

static void loadStatusCb(WebKitWebView *web_view, GParamSpec *pspec, void* context)
{
	WebKitLoadStatus status = webkit_web_view_get_load_status (web_view);
	GObject *object = G_OBJECT (web_view);
	g_object_freeze_notify (object);

	switch (status)
	{
		case WEBKIT_LOAD_FINISHED:
			//SLOG(DEBUG) << "WEBKIT_LOAD_FINISHED";
			handleLoadFinished(web_view, context);
			break;
		/*
		case WEBKIT_LOAD_PROVISIONAL:
			//SLOG(DEBUG) << "WEBKIT_LOAD_PROVISIONAL";
			//handleLoadProvisional(web_view, context);
			break;
		case WEBKIT_LOAD_COMMITTED:
			//SLOG(DEBUG) << "WEBKIT_LOAD_COMMITTED";
			//handleLoadCommitted(web_view, context);
			break;

		case WEBKIT_LOAD_FIRST_VISUALLY_NON_EMPTY_LAYOUT:
			//SLOG(DEBUG) << WEBKIT_LOAD_FIRST_VISUALLY_NON_EMPTY_LAYOUT";
			//handleLoadNonEmptyLayout(web_view, context);
			break;
		case WEBKIT_LOAD_FAILED:
			//SLOG(DEBUG) << "WEBKIT_LOAD_FAILED";
			//handleLoadFailed(web_view, context);
			break;
		*/
		default:
			break;

	}

	g_object_thaw_notify (object);
}

static void handleLoadFinished(WebKitWebView *web_view, void* context)
{
	/*
	WebKitDOMDocument *document = webkit_web_view_get_dom_document(WEBKIT_WEB_VIEW(web_view));
	WebKitDOMNodeList *elements = webkit_dom_document_get_elements_by_tag_name(document, "*");
	gulong element_count = webkit_dom_node_list_get_length(elements);

	for (int i = 0; i < element_count; i++)
	{
		WebKitDOMNode *element = webkit_dom_node_list_item(elements, i);
		g_assert(element);

		WebKitDOMElement* domElement = (WebKitDOMElement*)element;
		g_assert(domElement);
		char *val = webkit_dom_element_get_tag_name(domElement);

		SLOG(DEBUG) << val;

		g_free (val);
	}

	g_object_unref(elements);
	*/

	/*
	const gchar* title = webkit_web_view_get_title(web_view);
	SLOG(DEBUG) << "TITLE: " << title;
	*/

	WebKitWebFrame *frame = webkit_web_view_get_main_frame(web_view);
	webkit_web_frame_stop_loading(frame);

	WebKitWebSettings *settings = webkit_web_view_get_settings(web_view); 
	g_object_set(G_OBJECT(settings), "enable-scripts", TRUE, NULL);
	webkit_web_view_execute_script(web_view, scriptStr.c_str());
	g_object_set(G_OBJECT(settings), "enable-scripts", FALSE, NULL);
	
	SLOG(DEBUG) << "Finished";
	//SLOG(INFO) << "_TITLE";
	finished = true;
}


static void lbh_resource_request_starting_cb(WebKitWebView *web_view,
									WebKitWebFrame        *frame,
									WebKitWebResource     *resource,
									WebKitNetworkRequest  *request,
									WebKitNetworkResponse *response,
									gpointer                data)
{

	const gchar *uri = webkit_network_request_get_uri(request);
	SLOG(DEBUG) << "Requested_URI: " << uri;

	//const gchar *mime_type = webkit_web_resource_get_mime_type(resource);
	//const gchar *frame_name = webkit_web_resource_get_frame_name(resource);
	//SLOG(DEBUG) << "MIME_TYPE: " << mime_type;
	//SLOG(DEBUG) << "FRAME_NAME: " << frame_name;

	//gchar* method;
	//SoupMessage *msg = webkit_network_request_get_message(request);
	/*
	if (msg) {
	}
	*/
	//g_object_get(G_OBJECT(msg), SOUP_MESSAGE_METHOD, method);
	//SLOG(DEBUG) << "HDR_MEGHOD: " << method;
	//g_print("HDR_METHOD: %s\n", method);

	//SoupMessageHeaders *headers;
	//SoupMessageBody *msgBody;
	//g_object_get(msg, SOUP_MESSAGE_REQUEST_HEADERS, headers);
	//g_object_get(msg, SOUP_MESSAGE_REQUEST_BODY, msgBody);
	//soup_message_headers_foreach(headers, SoupMessageHeadersForeachFunc(headerForeachFunc), NULL);


	bool *allow_load = (bool*)(data);

	if(*allow_load == false) {
		webkit_network_request_set_uri(request, "about:blank");
		SLOG(DEBUG) << "BLOCK";
		return;
	}
	
	SLOG(DEBUG) << "ALLOW";
	*allow_load = false;

}

static void headerForeachFunc(const char *name, const char *value, gpointer data)
{
	SLOG(DEBUG) << name << ", " << value;
}
